//加油啊！不要绝望！
#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(){
    //创建套接字
    int socket_fd = socket(AF_INET,SOCK_STREAM,0);
    //绑定套接字
     //先创建一个struct sockaddr_in结构体对象并填充
    struct sockaddr_in serv_addr;
     //将内部清零
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY; // INADDR_ANY表示监听所有的接口
    serv_addr.sin_port = htons(8080);       // 填充端口号

    if(bind(socket_fd,(sockaddr*)(&serv_addr),sizeof(serv_addr)) != 0){
        perror("bind failed");
        close(socket_fd);
        exit(EXIT_FAILURE);
    }
    //监听套接字
    int length = 1;
    if(listen(socket_fd,length)!=0){
        perror("listen failed");
        close(socket_fd);
        exit(EXIT_FAILURE);
    }
    //连接套接字
    struct sockaddr_in cilent_addr;
    memset(&cilent_addr,0,sizeof(cilent_addr));
    socklen_t cilent_len = sizeof(cilent_addr);
    int connect_fd = accept(socket_fd,(sockaddr*)(&cilent_addr),&cilent_len);
    if(connect_fd == -1){
        perror("accpet failed");
        close(socket_fd);
        exit(EXIT_FAILURE);
    }
    int flag = 1;
    while(flag){
        char recv_buff[1024];
        //这里用于发送数据和接受数据
        recv(connect_fd,recv_buff,sizeof(recv_buff),0);
        std::cout<<"cilent say:"<<recv_buff<<std::endl;

        char send_buff[1024] = "server have got it!";
        send(connect_fd,send_buff,sizeof(send_buff),0);
    }
    close(socket_fd);
    close(connect_fd);
    return 0;  
}